package com.panda.web.utils.task;

import com.panda.web.entity.product.OpenidProduct;
import com.panda.web.entity.wechat.WechatUser;
import com.panda.web.mapper.product.OpenidProductMapper;
import com.panda.web.mapper.wechat.WechatUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Component
public class WechatUserTask {


    @Autowired
    WechatUserMapper userMapper;
    @Async
    @Scheduled(cron = "0 0/10 * * * ?") // 每 10 分钟执行一次
    public void dailyTask() {
        synchronized (this) { // 使用 synchronized 锁来保证任务的互斥执行
            List<WechatUser> wechatUsers = userMapper.selectByList();
            Date currentDate = new Date(); // 获取当前时间

            for (WechatUser wechatUser : wechatUsers) {
                if (Objects.equals(wechatUser.getTrialStatus(), "1")) { // 试用状态为 "1"（进行中）
                    String trialEndTime = wechatUser.getTrialEndTime(); // 获取试用结束时间
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    try {
                        // 将试用结束时间字符串解析为 Date 类型
                        Date endDate = simpleDateFormat.parse(trialEndTime);

                        if (currentDate.after(endDate)) { // 如果当前时间超过了试用结束时间
                            wechatUser.setTrialStatus("2"); // 更改状态为 "2"
                            userMapper.updateById(wechatUser); // 更新数据库
                        }
                    } catch (ParseException e) {
                        // 处理日期解析异常
                        e.printStackTrace();
                    }
                }
            }
        }
    }



}